<template>
    <div class="common-page page-org-clients" v-loading.fullscreen="loading">
        <div class="common-page__head">
            <!-- <comp-paths class="route" :paths="['/org', $route.fullPath]"></comp-paths> -->
            <div class="title">{{ $options.title }}</div>
        </div>
        <comp-clients class="common-page__body" ref="list" select link>
            <template #head="scope">
                <el-button type="plain" size="small" icon="el-icon-refresh" @click="search()">刷新列表</el-button>
                <el-button type="primary" size="small" icon="el-icon-plus" @click="addClient()">添加用户</el-button>
                <el-dropdown trigger="click">
                    <el-button type="plain" size="small" icon="el-icon-upload2">导入用户</el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="importClientsHolder()">导入服务专员</el-dropdown-item>
                        <el-dropdown-item @click.native="importClientsOfficer()">导入后援服务单位</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
                <!-- <el-dropdown trigger="click">
                    <el-button type="plain" size="small" icon="el-icon-download">导出用户</el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="exportClientsHolder()">导出服务专员信息</el-dropdown-item>
                        <el-dropdown-item @click.native="exportClientsOfficer()">导出后援服务单位信息</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown> -->
            </template>
            <template #body="scope">
                <el-button type="primary" size="mini" @click.stop="getClient(scope.data)">详情</el-button>
            </template>
        </comp-clients>
        <comp-dialog title="添加用户" width="360px" ref="client"  @close="closedep">
            <el-form size="small" label-width="98px" @submit.native.prevent v-if="client">
                <el-form-item label="部门：" required>
                    <div>
                        <el-tag v-if="depData" style="margin: 0 10px 10px 0" disable-transitions>{{depData.name}}</el-tag>
                    </div>
                    <div v-if="depData"></div>
                    <el-button type="plain" icon="el-icon-plus" @click="setClient('')">{{ depData ? "更换部门" : "选择部门" }}</el-button>
                </el-form-item>
                <el-form-item label="头像：">
                    <img style="display: block; margin: 0 10px 10px 0; max-width: 120px; height: 60px" :src="client.avatar" v-if="client.avatar" />
                    <el-button type="plain" icon="el-icon-plus" @click="addClient('upload-avatar')">{{ client.avatar ? "更换图片" : "选择图片" }}</el-button>
                </el-form-item>
                <el-form-item label="工号：" required>
                    <el-input ref="clientNumber" v-model="client.number" style="width: 240px" placeholder="请输入" :maxlength="20" :readonly="loading" @change="addClient('validate')"></el-input>
                </el-form-item>
                <el-form-item label="姓名：" required>
                    <el-input v-model="client.name" style="width: 240px" placeholder="请输入" :maxlength="20" :readonly="loading" @change="addClient('validate')"></el-input>
                </el-form-item>
                <el-form-item label="性别：" required>
                    <el-radio-group v-model="client.sex" @change="addClient('validate')">
                        <el-radio v-for="data in env.userSexs" :key="data.id" :label="data.value">{{ data.name }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="身份证号：">
                    <el-input v-model="client.sequence" style="width: 240px" placeholder="请输入" :maxlength="20" :readonly="loading" @change="addClient('validate')"></el-input>
                </el-form-item>
                <el-form-item label="手机号：">
                    <el-input v-model="client.mobile" style="width: 240px" placeholder="请输入" :maxlength="20" :readonly="loading" @change="addClient('validate')"></el-input>
                </el-form-item>
                <el-form-item label="角色：" required>
                    <el-select v-model="client.role" style="width: 160px" @change="addClient('validate')">
                        <el-option key="100" label="服务专员" value="holder">服务专员</el-option>
                        <el-option key="300" label="后援服务单位" value="officer">后援服务单位</el-option>

                        <!-- <el-option v-for="data in env.userRoles" :key="data.id" :label="data.name" :value="data.value">{{ data.name }}</el-option> -->
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="addClient('submit')">添加</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="addClient('end')">放弃</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
         <el-dialog
            title="选择部门"
           
           
            :visible.sync="opendep"
            width="840px"
           
            >
            
            <div style="height:60vh;width:800px" class="">
                <depts style="height: 100%" ref="deptPickerList" expanded @getsetletDept="getsetletDept">
                
                </depts>
            </div>
            
            </el-dialog>
        <comp-dialog title="从 Excel 导入服务专员" width="360px" ref="clientsHolderImportForm">
            <comp-import template="./data/UserAccountRole100ImportTemplate.xlsx" @start="importClientsHolder('submit', $event)" @end="importClientsHolder('end')"></comp-import>
        </comp-dialog>
        <comp-dialog title="从 Excel 导入后援服务单位" width="360px" ref="clientsOfficerImportForm">
            <comp-import template="./data/UserAccountRole300ImportTemplate.xlsx" @start="importClientsOfficer('submit', $event)" @end="importClientsOfficer('end')"></comp-import>
        </comp-dialog>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { string, int, toMagicImgURL, selectFile } from "../util";
    import depts from "../compents/depts.vue";
import Dialog from '../comps/dialog.vue';

    export default {
        name: "page-org-clients",
        title: "用户管理",
        nodes: ["/menu/org"],
        childs: ["org-client", "org-client-companys", "org-client-attendances"],
        mixins: [mixin],
        data: () => ({
            loading: false,
            client: null,
            depData:null,
            opendep:false,
        }),
          components: {
         depts,
                    Dialog
        },
        methods: {
            closedep(){
                this.depData = null;
                console.log(11111);
            },
              getsetletDept(infom){
                this.depData = infom;
                this.opendep = false;
                

            },
            search() {
                if (this.loading) return;
                this.$nextTick(() => this.$refs.list.init());
            },
            setClient(){
                    this.opendep = true;

            },
            addClient(action, data) {

                // let error = "";
                // error = error || (form.deptId ? "" : "1111");

                if (this.loading) return;
                let form = this.client;
                if (!action || action === "start") {
                    this.client = this.plugins.user.formatClient();
                    this.addClient("validate");
                    this.$refs.client.init();
                    this.$nextTick(() => this.$refs.clientNumber.focus());
                } else if (action === "validate") {
                    let error = "";
                    if(this.depData){
                        form.deptId = this.depData.id;

                    }

                    form.number = string(form.number).replace(/\s+/g, "");
                    error = error || (form.number ? "" : "请输入工号！");
                    error = error || (form.deptId ? "" : "请选择部门");
                    form.name = string(form.name).trim();
                    error = error || (form.name ? "" : "请输入姓名！");
                    form.sex = form.sex || this.env.userSexs[0].value;
                    form.sequence = string(form.sequence).trim();
                    form.mobile = string(form.mobile).trim();
                    error = error || (form.mobile ? /^1[3-9]\d{9}$/.test(form.mobile) ? "" : "手机号格式不正确！" : "");
                    form.role = form.role || this.env.userRoles[0].value;
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                }
                 else if (action === "upload-avatar") {
                    if (!data) return selectFile("image/*").then((file) => {
                        if (file.size > 5 * 1048576) this.plugins.modal.toast("图片过大，不能大于5MB哦！请重新选择。", "error");
                        else this.addClient(action, file);
                    });
                    let timer = null;
                    let progress = (event) => timer = clearTimeout(timer) || setTimeout(() => this.plugins.modal.toast("上传进度：" + event.percent + "%", "info"), 200);
                    this.loading = true;
                    this.plugins.user.uploadFile(data, "image", progress).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            form.avatar = toMagicImgURL(res.data.value, 120, 120);
                            this.addClient("validate");
                        } else {
                            this.plugins.modal.alert("图片上传失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "submit") {
                    if (!this.addClient("validate", true)) return;
                    this.loading = true;
                    this.plugins.user.addClient(form).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("添加成功！", "success");
                            this.addClient("end");
                            this.search();
                        } else {
                            this.plugins.modal.alert("添加失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.client.close();
                }
            },
            getClient(client) {
                if (this.loading) return;
                this.$router.push("/org/client?clientId=" + client.id);
            },
            importClientsHolder(action, data) {
                if (this.loading) return;
                if (!action || action === "start") {
                    this.$refs.clientsHolderImportForm.init();
                } else if (action === "submit") {
                    this.loading = true;
                    this.plugins.user.importClientsHolder({ file: data }).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.alert("导入任务创建成功！", "任务执行需要花费一些时间，可稍后再点击右上角打开“系统任务”查看任务状态。", "success", ["查看任务状态", "稍后查看"]).then((ok) => ok && this.$router.push("/user/tasks"));
                            this.importClientsHolder("end");
                            this.search();
                        } else {
                            this.plugins.modal.alert("导入失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.clientsHolderImportForm.close();
                }
            },
            importClientsOfficer(action, data) {
                if (this.loading) return;
                if (!action || action === "start") {
                    this.$refs.clientsOfficerImportForm.init();
                } else if (action === "submit") {
                    this.loading = true;
                    this.plugins.user.importClientsOfficer({ file: data }).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.alert("导入任务创建成功！", "任务执行需要花费一些时间，可稍后再点击右上角打开“系统任务”查看任务状态。", "success", ["查看任务状态", "稍后查看"]).then((ok) => ok && this.$router.push("/user/tasks"));
                            this.importClientsOfficer("end");
                            this.search();
                        } else {
                            this.plugins.modal.alert("导入失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.clientsOfficerImportForm.close();
                }
            },
            exportClientsHolder() {
                if (this.loading) return;
                let content = " <span style='color:red;'>全部服务专员信息</span> ";
                let callback = () => {
                    this.loading = true;
                    this.plugins.user.exportClientsHolder().then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.alert("导出任务创建成功！", "任务执行需要花费一些时间，可稍后再点击右上角打开“系统任务”查看任务状态。", "success", ["查看任务状态", "稍后查看"]).then((ok) => ok && this.$router.push("/user/tasks"));
                        } else {
                            this.plugins.modal.alert("导出失败", res.code + "：" + res.msg, "error");
                        }
                    });
                };
                this.plugins.modal.alert("批量导出", "确定导出" + content + "吗？", "warning", ["确定导出", "再想想"]).then((ok) => ok && callback());
            },
            exportClientsOfficer() {
                if (this.loading) return;
                let content = " <span style='color:red;'>全部后援服务单位信息</span> ";
                let callback = () => {
                    this.loading = true;
                    this.plugins.user.exportClientsOfficer().then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.alert("导出任务创建成功！", "任务执行需要花费一些时间，可稍后再点击右上角打开“系统任务”查看任务状态。", "success", ["查看任务状态", "稍后查看"]).then((ok) => ok && this.$router.push("/user/tasks"));
                        } else {
                            this.plugins.modal.alert("导出失败", res.code + "：" + res.msg, "error");
                        }
                    });
                };
                this.plugins.modal.alert("批量导出", "确定导出" + content + "吗？", "warning", ["确定导出", "再想想"]).then((ok) => ok && callback());
            },
            destroy() {
                if (this.loading) return;
                return true;
            },
            init() {
                if (this.loading) return;
                this.loading = true;
                this.$root.$refs.navbar.init();
                this.plugins.user.call(async () => {
                    let res = await this.plugins.user.init();
                    if (res.code === 0) { }
                    return res;
                }, async () => {
                    if (this.access(this.$route.name)) return { code: 0 };
                    return this.env.xhrErrors.find((error) => error.code === 4);
                }).then((res) => {
                    this.loading = false;
                    this.$root.$refs.navbar.init();
                    if (res.code === 0) {
                        this.search();
                    } else if (res.code === 2) {
                        this.$root.$refs.navbar.login();
                    } else {
                        this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/home"));
                    }
                });
            },
        },
    };
</script>

<style lang="scss">
    .page-org-clients {
        overflow: hidden;
    }
    .iii{
        height: 800px;
    }
</style>